package com.wyh.blog.filter;

import com.wyh.blog.constant.consist.Constants;
import com.wyh.blog.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader(Constants.USER_TOKEN_HEADER_KEY);
        log.info("从Header中获取并校验token, userToken: {}", userToken);
        if (!StringUtils.hasLength(userToken)){
            response.setStatus(401);//401表示用户未登录
            return false;
        }
        Claims claims = JwtUtil.parseJwt(userToken);
        if (claims == null) {
            response.setStatus(401);//401表示用户未登录
            return false;
        }
        return true;
    }
}
